package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.userDto.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author 13691
 * @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
 */
@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>
        implements ApUserService {


    @Override
    public ResponseResult appLogin(LoginDto loginDto) {
        log.info("app用户登录");
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();
        // 账号或者密码为空进行游客访问
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(password)) {
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            return ResponseResult.okResult(resultMap);
        }
        // 根据手机查询用户信息
        LambdaQueryWrapper<ApUser> queryWrapper = Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone);
        ApUser apUser = this.getOne(queryWrapper);
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 用户存在，校验密码
        String apUserPassword = apUser.getPassword();
        String salt = apUser.getSalt();
        String cryptPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        // 密码错误返回错误提示
        if (!StringUtils.equals(cryptPassword, apUserPassword)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 生成token
        String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));

        // 信息脱敏,封装返回数据
        apUser.setSalt("");
        apUser.setPassword("");
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", apUser);
        resultMap.put("token", token);
        return ResponseResult.okResult(resultMap);
    }
}




